#ifndef COMMON
#define COMMON
#include "bios.h"

#define UP     0x48
#define DOWN   0x50
#define RIGHT  0x4d
#define LEFT   0x4b
#define ESC    27
#define ENTER  13
#define DELETE 0x53
#define BACKSPACE 0X8

#define KEY union key

union key
{
 int key;
 char ch[2];
};

typedef enum {FALSE=0,TRUE=1} Bool;
typedef enum {ERROR=0,OK=1,OVERFLOW=-1} Status;

void insert(char *str,int cur,char ch)
{
 int i;
 for(i=strlen(str);i>=cur;i--)
 {
  str[i+1]=str[i];
 }
 str[cur]=ch;
}

void delete(char *str,int cur)
{
 int i;
 for(i=cur;i<strlen(str);i++)
 {
  str[i]=str[i+1];
 }
}

int get_str(char *str,int len)        /* If you want to get a new string. Please  */
{                                     /*use str[0]='\0'before using this function */
 KEY k;
 int x,y;
 int cur=0;
 int cend;

 cend=strlen(str);
 x=wherex();
 y=wherey();
 gotoxy(x,y);
 cprintf(str);
 gotoxy(x,y);

 while(1)
 {
  k.key=bioskey(0);
     if(k.ch[0])
     {
	 switch(k.ch[0])
	 {
	  case ESC:
	  return -1;
	  case ENTER:
	  return 1;
	  case BACKSPACE:
	      if(cur>0)
	      {
	       cur--;
	       delete(str,cur);
	       cend--;
	       delline();
	       gotoxy(x,y);
	       cprintf(str);
	       gotoxy(x+cur,y);
	      }
	  break;
	  default:
	      if(cend<len-2)
	      {
	       insert(str,cur,k.ch[0]);
	       cur++;
	       cend++;
	       delline();
	       gotoxy(x,y);
	       cprintf(str);
	       gotoxy(x+cur,y);
	      }
	  break;
	 }

     }
     else
     {
	 switch(k.ch[1])
	 {
	  case LEFT:
	  cur=cur<=0?cur:cur-1;
	  gotoxy(x+cur,y);
	  break;
	  case RIGHT:
	  cur=cur>=cend?cur:cur+1;
	  gotoxy(x+cur,y);
	  break;

	  case DELETE:
	      if(str[cur])
	      {
	       delete(str,cur);
	       cend--;
	       delline();
               gotoxy(x,y);
	       cprintf(str);
	       gotoxy(x+cur,y);
	      }
	  break;
	 }
     }
 }
}
#endif